package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.pojo.Type;
import com.itheima.pojo.TypePage;
import com.itheima.service.TypeService;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Envy
 */
@RestController
@RequestMapping("category")
public class TypeController {
    @Resource
    TypeService typeService;

    /**
     * 新增分类
     */
    @PostMapping()
    public R<Type> addType(@RequestBody Type type) {
        //获取时间戳,将时间戳作为id
        long timeMillis = System.currentTimeMillis();
        String id = timeMillis + "";
        type.setId(id);

        try {
            int i = typeService.addType(type);
            if (i != 0) {
                return R.success(type);
            }
        } catch (Exception e) {
            System.out.println("用户新增=============bug");
        }
        return R.error("新增失败,此菜系已存在");
    }

    /**
     * 分类信息分页查询
     */
    @GetMapping("/page")
    public R<TypePage> pageQuery(@Param("page") Integer page, @Param("pageSize") Integer pageSize) {
        Integer pageMin = (page - 1) * pageSize;
        return typeService.pageQuery(pageMin, pageSize);
    }

    /**
     * 分类下拉列表
     */
    @GetMapping("/list")
    public R<List<Type>> pullDown() {
        List<Type> types = typeService.pullDown();
        if (types.size() != 0) {
            return R.success(types);
        } else {
            return R.error("查询失败");
        }
    }

    /**
     * 删除分类
     */
    @DeleteMapping()
    public R<Object> delete(@RequestParam String id) {
        int delete = typeService.delete(id);
        if (delete != 0) {
            return R.success(delete);
        } else {
            return R.error("当前分类下关联了套餐，不能删除");
        }
    }

    /**
     * 编辑分类
     */
    @PutMapping()
    public R<Object> update(@RequestBody Type type) {
        try {
            int update = typeService.update(type);
            if (update != 0) {
                return R.success(update);
            }
        }catch (Exception e){
            return R.error("修改失败,此菜系已存在");
        }
        return R.error("修改信息失败");
    }
}
